using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using WPFServices.Commands;
using WPFServices.Models;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.ProcessRouteinfo;

namespace WPFServices.ViewModels.DomainViewModel.ProcessRouteinfo
{
    public class ProcessRouteSelectionViewModel : BaseViewModel
    {
        private readonly ProcessRouteService _processRouteService;
        private ObservableCollection<ProcessRouteDto> _processRoutes;
        private ProcessRouteDto _selectedProcessRoute;
        private bool _isLoading;
        private int _currentPage = 1;
        private int _pageSize = 10;
        private int _totalCount;
        private int _totalPages;

        public ProcessRouteSelectionViewModel()
        {
            _processRouteService = new ProcessRouteService();
            _processRoutes = new ObservableCollection<ProcessRouteDto>();

            LoadDataCommand = new RelayCommand(async _ => await LoadDataAsync());
            PreviousPageCommand = new RelayCommand(_ => PreviousPage(), _ => CurrentPage > 1);
            NextPageCommand = new RelayCommand(_ => NextPage(), _ => CurrentPage < TotalPages);
            ConfirmCommand = new RelayCommand(_ => Confirm(), _ => CanConfirm());
            CancelCommand = new RelayCommand(_ => Cancel());

            // 初始加载数据
            _ = LoadDataAsync();
        }

        public event Action<bool> CloseWindow;

        #region 属性
        public ObservableCollection<ProcessRouteDto> ProcessRoutes
        {
            get => _processRoutes;
            set => SetProperty(ref _processRoutes, value);
        }

        public ProcessRouteDto SelectedProcessRoute
        {
            get => _selectedProcessRoute;
            set => SetProperty(ref _selectedProcessRoute, value);
        }

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }
        #endregion

        #region 命令
        public RelayCommand LoadDataCommand { get; }
        public RelayCommand PreviousPageCommand { get; }
        public RelayCommand NextPageCommand { get; }
        public RelayCommand ConfirmCommand { get; }
        public RelayCommand CancelCommand { get; }
        #endregion

        #region 方法
        private async Task LoadDataAsync()
        {
            try
            {
                IsLoading = true;

                var searchDto = new SearchProcessRouteDto
                {
                    PageIndex = CurrentPage,
                    PageSize = PageSize
                };

                var result = await _processRouteService.SearchProcessRouteAsync(searchDto);
                
                ProcessRoutes.Clear();
                foreach (var processRoute in result.Data)
                {
                                    // 只显示启用的工艺路线（状态为1）
                if (processRoute.States.HasValue && processRoute.States.Value == 1)
                {
                    ProcessRoutes.Add(processRoute);
                }
                }

                TotalCount = result.TotalCount;
                TotalPages = (int)Math.Ceiling((double)TotalCount / PageSize);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载工艺路线列表失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private void PreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                _ = LoadDataAsync();
            }
        }

        private void NextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                _ = LoadDataAsync();
            }
        }

        private bool CanConfirm()
        {
            return SelectedProcessRoute != null;
        }

        private void Confirm()
        {
            CloseWindow?.Invoke(true);
        }

        private void Cancel()
        {
            CloseWindow?.Invoke(false);
        }
        #endregion
    }
} 